<template>
  <!-- 修改入库单 -->
  <div class="container">
    <div class="left">
      <div class="title">修改采购入库退货单</div>
      <!-- #436AE8 -->

      <div v-if="leftContent" class="codeInfo">
        <div>
          采购退货编号：<span style="color: #436ae8">{{
            leftContent.purchaseReturnOrderNo
          }}</span>
        </div>
        <div>
          制单人：{{ leftContent.createdName }}
        </div>
        <div>
          制单时间：{{
            $moment(leftContent.createdTime)
          }}
        </div>
      </div>

      <div class="leftContext">
        <el-table :data="leftContent.items">
          <el-table-column
            label="序号"
            type="index"
            width="55"
          ></el-table-column>

          <el-table-column label="供应商">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.supplierName
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="退货部门">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnOrgName
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="退货仓库">
            <template slot-scope="scope">
              <div  @click="openDetails(scope.row)">
                <p style="display:inline-block" v-for='items in scope.row.depotVOS' :key='items.returnDepotName'>
                    <span>{{ items.returnDepotName }}</span>
                    <span v-if='scope.row.depotVOS.length>1'>,</span>
                </p>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="退货商品" show-overflow-tooltip width="150px">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnProdName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="图片">
            <template slot-scope="scope">
              <img
                v-if="scope.row.orderPurchaseInOrderItem.inDepotProdImage"
                @click="openDetails(scope.row)"
                style="width: 50px; height: 50px"
                :src="ImgHttps + scope.row.orderPurchaseInOrderItem.inDepotProdImage"
                alt=""
              />
              <span v-else>/</span>
            </template>
          </el-table-column>
          <el-table-column label="入库类型">
            <template slot-scope="scope">
              <span
                @click="openDetails(scope.row)"
                v-if="scope.row.returnProdType == 1"
                >商品</span
              >
              <span @click="openDetails(scope.row)" v-else>赠品</span>
            </template>
          </el-table-column>
          <el-table-column label="退货品牌">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnProdBrandName
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="退货单价">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnProdPrice
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="退货数量">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnProdQuantity
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="退货金额" width="100px;">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.returnProdAmount
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="可退数量" width="80px;">
            <template slot-scope="scope">
              <span @click="openDetails(scope.row)">{{
                scope.row.addcanOperateQuantity
              }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="right">
      <div class="title">操作</div>
      <div class="rightContext" style="border: 0">
        <el-form ref="form" :model="form" label-width="90px">
          <el-form-item label="退货部门">
            <div class="selectTree">
              <treeselect
                disabled
                :options="options"
                v-model="form.returnOrgCode"
                search-nested
                :normalizer="normalizer"
                noResultsText="未找到"
                placeholder="请选择"
              >
              </treeselect>
            </div>
          </el-form-item>
          <el-form-item label="退货供应商">
            <el-input
              size="small"
              placeholder="供应商名称"
              :value="form.supplierName"
              supplierName
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货类型">
            <el-input
              size="small"
              placeholder="退货类型"
              :value="form.returnProdType == 1 ? '商品' : '赠品'"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货商品">
            <el-input
              size="small"
              placeholder="退货商品"
              :value="form.returnProdType"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货规格">
            <el-input
              size="small"
              placeholder="退货规格"
              :value="form.returnProdSpecificationName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货品牌">
            <el-input
              size="small"
              placeholder="退货品牌"
              :value="form.returnProdBrandName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货数量">
            <el-input
              disabled
              size="small"
              placeholder="退货数量"
              :value="form.returnProdQuantity"
            ></el-input>
          </el-form-item>
          <el-form-item label="退货金额">
            <el-input
              size="small"
              placeholder="退货金额"
              :value="form.returnProdAmount"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="退货仓库">
            <div
              v-for="(ite, index) in form.depotVOS"
              :key="index"
              v-if="ite.type == 0 || ite.type == undefined"
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
                min-width:450px;
              "
            >
              <el-select
                :value="ite.returnDepotName"
                size="mini"
                value-key="id"
                placeholder="请选择"
                disabled
                @change="myWareListChange($event, ite)"
              >
                <el-option
                  v-for="item in wareList.list"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
              <div style="display: flex; align-items: center">
                可退货数量{{ite.returnProdQuantity - ite.returnProdQuantity1}}
                <el-input-number
                  size="mini"
                  :min="0"
                  :max="ite.returnProdQuantity"
                  style="margin-right: 10px"
                  placeholder="请输入退货数量"
                  v-model="ite.returnProdQuantity1"
                  @change="inputChange(ite)"
                ></el-input-number>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="备注">
            <el-input maxlength="255" placeholder="请输入备注" type="textarea" v-model="textarea"></el-input>
          </el-form-item>
        </el-form>
        <p style="text-align: right; margin-top: 50px">
          <el-button type="primary" size="mini" @click="submit">确认</el-button>
        </p>
      </div>
    </div>
  </div>
</template>
<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  data() {
    return {
      table: {
        list: [],
        pageNo: 1,
        pageSize: 10,
      },
      form: {}, //表单数据
      wareList: {
        list: [],
      },
      leftContent: "",
      normalizer(node) {
        return {
          id: node.orgCode,
          label: node.orgName,
          children: node.children,
        };
      },
      options: [],
      textarea:""
    };
  },
  created() {
    this.listAxios(this.$route.query.id);
    this.department();
  },
  activated() {
    this.getWareList();
  },
  methods: {
    openDetails(row) {
      this.form = row;
    },
    // 部门选择列表
    department() {
      this.axios
        .post(
          "/sys/v1/org/tree/select",
          {
            request: {
              orgName: "",
              orgType: "",
            },
            version: "",
          },
          {
            headers: {
              isLoading: false,
            },
          }
        )
        .then((res) => {
          if (res.code == 0) {
            this.options = res.data;
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 数据请求
    listAxios(purchaseInOrderNo) {
      this.axios
        .get("/order/v1/purchase/return/order/returnPurchaseOrderDetails?id="+purchaseInOrderNo)
        .then((res) => {
          //   console.log(res);
          if (res.code == 0) {
            this.textarea = res.data.comment;
            let itemList = res.data.items;
            for (let i in itemList) {
              itemList[i].addcanOperateQuantity = Number(itemList[i].returnProdQuantity)+ Number(itemList[i].orderPurchaseInOrderItem.canOperateQuantity); //退货数量
              itemList[i].depotVOS.forEach(j => {
                j.returnProdQuantity1 = j.returnProdQuantity;
              })
            }
            this.leftContent = res.data;
            this.form = this.leftContent.items[0];
          } else {
            this.$message.error(res.message);
          }
        });
    },
    delectImgList(index) {
      this.form.fileListImg.splice(index, 1);
    },
    addMyWareList(param) {
      if (this.form.warehouses.length < this.wareList.list.length) {
        this.form.selectObj.push({
          comId: param.id,
          number: 0,
          warId: "",
          warName: "",
        });
      } else {
        this.$message.warning("不能再加了仓库只有这些");
      }
    },
    beforeUploadImg(file) {
      return new Promise((resolve, reject) => {
        let _URL = window.URL || window.webkitURL;
        let isLt2M = file.size / 1024 / 1024 > 4; // 判定图片大小是否小于4MB
        // 这里需要计算出图片的长宽
        let img = new Image();
        img.onload = function () {
          file.width = img.width; // 获取到width放在了file属性上
          file.height = img.height; // 获取到height放在了file属性上
          let valid = img.width > 2000; // 图片宽度大于2000
          // console.log(11, file)
          // 这里我只判断了图片的宽度,compressAccurately有多个参数时传入对象
          if (valid || isLt2M) {
            imageConversion
              .compressAccurately(file, {
                size: 400,
                width: 2000,
              })
              .then((res) => {
                // console.log(33, res)
                resolve(res);
              });
          } else resolve(file);
        }; // 需要把图片赋值
        img.src = _URL.createObjectURL(file);
      });
    },
    imgUpload(fileObj) {
      let length = this.form.fileListImg.length;
      let formData = new FormData();
      formData.append("file", fileObj.file);

      let config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      if (length <= 5) {
        this.axios
          .post(
            "/sys/v1/common/upload/files?pathName=internalSystem",
            formData,
            config,
            {
              headers: {
                isLoading: false,
              },
            }
          )
          .then((res) => {
            console.log(res);
            if (res.code == 0) {
              // this.imageUrl = res.data.url;
              let obj = {
                img: res.data.url,
                creattime: new Date().toLocaleDateString(),
              };
              this.form.fileListImg.push(obj);
            } else {
              this.$message.error(res.message);
            }
          });
      } else {
        this.$message.warning("图片条数不能超过10条");
      }
    },
    //删除现在的仓库
    deleteMyWare(e, t) {
      if (t) {
        let temp = this.form.selectObj.find((res) => res.warId === e.warId);
        temp.type = 1;
      } else {
        this.form.selectObj.splice(
          this.form.selectObj.findIndex((res) => res.warId == e.warId),
          1
        );
      }
      this.numberTotalWare();
    },
    //自己选择的仓库修改了
    myWareListChange(e1, e2) {
      let temp = this.form.orderPurchaseInOrderProdDepotList.find(
        (res) => e1.id == res.warId
      );
      if (temp) {
        if (temp.type) {
          this.$message.warning("该仓库已删除不能选");
        } else {
          this.$message.warning("该仓库已存在");
        }
        return;
      }
      e2.warId = e1.id + "";
      e2.warName = e1.name;
      this.$forceUpdate();
    },
    inputChange(e) {
      this.numberTotalWare();
    },
    // 计算退货数量
    numberTotalWare() {
      let numberTotal = 0;
      for (let i in this.form.depotVOS) {
        if(this.form.depotVOS[i].returnProdQuantity1){
          numberTotal += this.form.depotVOS[i].returnProdQuantity1;
        }else{
          this.form.depotVOS[i].returnProdQuantity1 = 0;
        }
      }
      this.form.returnProdAmount = numberTotal * this.form.returnProdPrice;
      this.form.returnProdQuantity = numberTotal;
    },
    getWareList() {
      this.axios
        .post("order/comm/commWarehouse/list",{
        pageSize:999,
        pageNo:1
      }, {
          isLoading: false,
        })
        .then((res) => {
          //仓库数据接口
          this.wareList = res.data;
          this.wareList.list = this.wareList.list.reverse();
        });
    },

    // 数据提交
    submit: _.debounce(function () {
      // 数据处理
      let itemList = [];
      let items = this.leftContent.items;
      for (let i in items) {
        // 仓库数据过滤 统计退货总数量
        items[i].backDepotList = [];
        for (let u in items[i].depotVOS) {
          items[i].backDepotList.push({
            inOrderProdDepotId:items[i].depotVOS[u].inOrderProdDepotId,
            returnDepotId:items[i].depotVOS[u].returnDepotId,
            returnDepotName:items[i].depotVOS[u].returnDepotName,
            returnProdQuantity:items[i].depotVOS[u].returnProdQuantity1,
          })
        }
 
        //   判断入库数据的对错
        if (items[i].returnProdQuantity>items[i].addcanOperateQuantity) {
          this.$message.warning(
            items[i].returnProdName + ",退货数量不能大于可退数量"
          );
          return false;
        }

        itemList.push({
          depots: items[i].backDepotList,//仓库
          orderPurchaseInOrderItemId: items[i].orderPurchaseInOrderItemId,//采购入库订单明细ID
          returnOrgCode: items[i].returnOrgCode,
          returnOrgName: items[i].returnOrgName,
          returnProdAmount:items[i].returnProdAmount,
          returnProdImage:items[i].returnProdImage,
          returnProdQuantity:items[i].returnProdQuantity,
        });
      }
    
     this.axios.post('/order/v1/purchase/return/order/updateReturnPurchaseOrder',{
        itemList:itemList,
        purchaseInOrderNo: this.leftContent.purchaseInOrderNo,
        purchaseReturnOrderNo: this.leftContent.purchaseReturnOrderNo,
        comment:this.textarea
     }).then(res=>{
       if(res.code == 0){
         this.$message.success('修改成功');
         this.$router.go(-1);
       }else{
         this.$message.error(res.message)
       }
     })

    //  this.$router.push({
    //      name:"returnInformation",
    //      query:{
    //          itemList:JSON.stringify(itemList),
    //          content:JSON.stringify({
    //           purchaseInOrderNo:this.$route.query.purchaseInOrderNo, //采购入库订单号
    //           purchaseReturnOrderNo: this.leftContent.purchaseReturnOrderNo,//退货订单号
    //           createdTime: this.leftContent.orderPurchaseInOrderBase.createdTime,
    //           createdName: this.leftContent.orderPurchaseInOrderBase.createdName,
    //         }),
    //      }
    //  })
    }, 300),

    // 递归
    getMenuBtnList(menuTreeList, menuList, code) {
      for (let item of menuTreeList) {
        if (item.orgCode == code) {
          menuList.push({
            lable: item.orgName,
            orgCode: item.orgCode,
            type: item.type,
          });
        } else if (item.children && item.children.length > 0) {
          this.getMenuBtnList(item.children, menuList, code);
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  height: 100%;
  .left {
    overflow: auto;
    background: #fff;
    padding: 10px;
    flex: 1;
    min-width: 600px;
    .title {
      color: #6b6b6b;
      font-size: 16px;
      border-bottom: 2px solid #e3e7ec;
      padding-bottom: 10px;
    }
    .leftContext {
      margin-top: 10px;
      border: 1px solid#E3E7EC;
    }
  }
  .right {
    overflow: auto;
    flex: 1;
    background: #fff;
    padding: 10px;
    margin-left: 10px;
    min-width: 400px;
    .title {
      color: #6b6b6b;
      font-size: 16px;
      border-bottom: 2px solid #e3e7ec;
      padding-bottom: 10px;
    }
    .rightContext {
      margin-top: 10px;
      border: 1px solid#E3E7EC;
    }
  }
}
.codeInfo {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
  div {
    font-size: 15px;
    color: #666;
  }
}
/deep/.el-table th > .cell {
  color: #333;
}
/deep/.el-form-item {
  margin-bottom: 10px;
}
.liimg {
  position: relative;
  display: inline-block;
  margin-right: 12px;
  width: 80px;

  p {
    text-align: center;
    font-size: 12px;
    color: #666;
  }

  .close {
    position: absolute;
    top: -20px;
    right: -10px;
    z-index: 10;
  }

  .close:hover {
    cursor: pointer;

    i {
      color: #006af1;
    }
  }

  .img-avatar {
    width: 80px;
    height: 80px;
    border-radius: 5px;
  }
}

.selectTree {
  width: 100%;
  display: inline-block;
  vertical-align: middle;
  margin-right: 10px;
  height: 30px;

  /deep/.el-cascader .el-input .el-input__inner {
    line-height: 30px;
    height: 30px;
    width: 100%;
  }
  /deep/.el-cascader .el-input {
    width: 250px;
  }
}
/deep/.vue-treeselect {
  height: 30px;
}
/deep/.vue-treeselect--searchable .vue-treeselect__input-container {
  height: 30px;
  line-height: 30px;
}
/deep/.vue-treeselect__single-value {
  font-size: 14px;
  line-height: 30px;
}
/deep/.vue-treeselect__menu-container {
  font-size: 15px;
}
/deep/.vue-treeselect__multi-value-item {
  height: 20px;
  line-height: 20px;
  padding: 0;
}
/deep/.vue-treeselect__input {
  height: 28px;
  line-height: 28px;
  outline: none;
  border: none;
  padding: 0;
  // display: none;
  // border:1px solid #000;
}
/deep/.vue-treeselect__placeholder {
  font-size: 10px;
  line-height: 28px;
}
/deep/.vue-treeselect--has-value .vue-treeselect__multi-value {
  margin: 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
/deep/.vue-treeselect__control {
  height: 30px;
}
</style>